<template>
	<s-layout class="live-streaming-wrap" title="开启直播" :bgStyle="{ color: '#000000' }" navbar="custom">
		<!-- 直播预览区域 -->
		<view class="live-pusher-container">
			<live-pusher
				id="livePusher"
				ref="livePusherRef"
				class="live-pusher"
				:url="state.pushUrl"
				:mode="state.mode"
				:beauty="state.beauty"
				:whiteness="state.whiteness"
				:aspect="state.aspect"
				:min-bitrate="state.minBitrate"
				:max-bitrate="state.maxBitrate"
				:audio-quality="state.audioQuality"
				:waiting-image="state.waitingImage"
				:zoom="state.enableZoom"
				:device-position="state.devicePosition"
				:background-mute="state.backgroundMute"
				:remote-mirror="state.remoteMirror"
				:local-mirror="state.localMirror"
				:audio-reverb-type="state.audioReverbType"
				:enable-camera="state.enableCamera"
				:enable-mic="state.enableMic"
				:auto-focus="state.autoFocus"
				:orientation="state.orientation"
				@statechange="onStateChange"
				@netstatus="onNetStatus"
				@error="onError"
				@bgmstart="onBgmStart"
				@bgmprogress="onBgmProgress"
				@bgmcomplete="onBgmComplete"
			/>

			<!-- 直播状态显示区域 -->
			<view class="live-status-bar">
				<view class="status-item">
					<text class="status-label">状态:</text>
					<text :class="['status-value', state.isLiving ? 'status-live' : '']">{{ state.liveStatus }} </text>
				</view>
				<view class="status-item" v-if="state.netStatus.speed">
					<text class="status-label">网速:</text>
					<text class="status-value">{{ state.netStatus.speed }}KB/s</text>
				</view>
				<view class="status-item" v-if="state.netStatus.bitrate">
					<text class="status-label">码率:</text>
					<text class="status-value">{{ state.netStatus.bitrate }}kbps</text>
				</view>
			</view>

			<!-- 控制按钮区域 -->
			<view class="control-panel">
				<!-- 美颜控制 -->
				<view class="control-group">
					<view class="control-item">
						<text class="control-label">美颜</text>
						<slider class="control-slider" :value="state.beauty" min="0" max="9" show-value @change="onBeautyChange" />
					</view>
					<view class="control-item">
						<text class="control-label">美白</text>
						<slider class="control-slider" :value="state.whiteness" min="0" max="9" show-value @change="onWhitenessChange" />
					</view>
				</view>

				<!-- 功能按钮组 -->
				<view class="button-group">
					<view class="control-btn" @tap="switchCamera">
						<uni-icons type="camera" size="24" color="#ffffff"></uni-icons>
						<text class="btn-text">切换摄像头</text>
					</view>
					<view class="control-btn" @tap="toggleFlash">
						<uni-icons :type="state.enableFlash ? 'hand-up' : 'hand-down'" size="24" color="#ffffff"></uni-icons>
						<text class="btn-text">{{ state.enableFlash ? '关闭闪光灯' : '开启闪光灯' }}</text>
					</view>
					<view class="control-btn" @tap="toggleMute">
						<uni-icons :type="state.enableMic ? 'mic-filled' : 'mic'" size="24" color="#ffffff"></uni-icons>
						<text class="btn-text">{{ state.enableMic ? '关闭麦克风' : '开启麦克风' }}</text>
					</view>
				</view>

				<!-- 清晰度选择 -->
				<view class="quality-selector">
					<text class="selector-label">清晰度:</text>
					<radio-group class="radio-group" @change="onModeChange">
						<label class="radio-item" v-for="(item, index) in state.modeOptions" :key="index">
							<radio :value="item.value" :checked="state.mode === item.value" color="#36D1DC" />
							<text class="radio-text">{{ item.label }}</text>
						</label>
					</radio-group>
				</view>

				<!-- 开始/停止直播按钮 -->
				<view :class="state.isLiving ? 'start-btn stop-btn' : 'start-btn'" @tap="toggleLive">
					<text>{{ state.isLiving ? '结束直播' : '开始直播' }}</text>
				</view>
			</view>
		</view>
	</s-layout>
</template>

<script setup>
	import { ref, reactive, onMounted, onUnmounted } from 'vue';
	import sheep from '@/sheep';

	// 直播推流器引用
	const livePusherRef = ref(null);

	// 状态管理
	const state = reactive({
		// 推流地址
		pushUrl: '',
		// 是否正在直播
		isLiving: false,
		// 直播状态文本
		liveStatus: '未开始',
		// 网络状态信息
		netStatus: {},
		// 摄像头位置 front/back
		devicePosition: 'front',
		// 美颜级别 0-9
		beauty: 5,
		// 美白级别 0-9
		whiteness: 5,
		// 闪光灯开关
		enableFlash: false,
		// 麦克风开关
		enableMic: true,
		// 摄像头开关
		enableCamera: true,
		// 自动对焦
		autoFocus: true,
		// 推流模式
		mode: 'SD',
		// 清晰度选项
		modeOptions: [
			{ label: '标清', value: 'SD' },
			{ label: '高清', value: 'HD' },
			{ label: '超清', value: 'FHD' },
		],
		// 宽高比
		aspect: '9:16',
		// 最小码率
		minBitrate: 200,
		// 最大码率
		maxBitrate: 1000,
		// 音频质量
		audioQuality: 'high',
		// 等待图像
		waitingImage: '',
		// 启用缩放
		enableZoom: false,
		// 背景静音
		backgroundMute: false,
		// 远程镜像
		remoteMirror: false,
		// 本地镜像
		localMirror: 'auto',
		// 音频混响类型
		audioReverbType: 0,
		// 方向
		orientation: 'vertical',
		// 错误信息
		errorMsg: '',
		// 权限状态
		permissionState: {
			camera: false,
			microphone: false,
		},
		// 加载状态
		loading: false,
	});

	// 生命周期 - 页面加载
	onLoad(async () => {
		// 检查权限
		await checkPermissions();
		// 获取推流地址
		await getPushUrl();
	});

	// 生命周期 - 组件挂载
	onMounted(() => {
		// 初始化直播推流器上下文
		initLivePusherContext();
	});

	// 生命周期 - 组件卸载
	onUnmounted(() => {
		// 确保结束直播
		if (state.isLiving) {
			stopPush();
		}
	});

	// 初始化直播推流器上下文
	let livePusherContext = null;
	const initLivePusherContext = () => {
		// 创建推流上下文
		livePusherContext = uni.createLivePusherContext('livePusher', this);
	};

	// 检查权限
	const checkPermissions = async () => {
		try {
			// 检查摄像头权限
			// const cameraRes = await uni.authorize({ scope: 'scope.camera' });
			state.permissionState.camera = true;

			// 检查麦克风权限
			// const microphoneRes = await uni.authorize({ scope: 'scope.record' });
			state.permissionState.microphone = true;

			return true;
		} catch (error) {
			console.error('权限检查失败:', error);
			sheep.$helper.toast('请授予摄像头和麦克风权限');

			// 引导用户开启权限
			uni.showModal({
				title: '提示',
				content: '直播功能需要摄像头和麦克风权限，请在设置中开启',
				confirmText: '去设置',
				success: (res) => {
					if (res.confirm) {
						uni.openSetting();
					}
				},
			});

			return false;
		}
	};

	// 获取推流地址
	const getPushUrl = async () => {
		try {
			state.loading = true;
			// 调用API获取推流地址
			const res = await sheep.$api.yy.liveAdd();
			if (res.code === 1) {
				state.pushUrl = res.data.pushurl;
				return true;
			} else {
				sheep.$helper.toast(res.msg || '获取推流地址失败');
				return false;
			}
		} catch (error) {
			console.error('获取推流地址失败:', error);
			sheep.$helper.toast('获取推流地址失败');
			return false;
		} finally {
			state.loading = false;
		}
	};

	// 开始推流
	const startPush = () => {
		if (!state.pushUrl) {
			sheep.$helper.toast('推流地址不能为空');
			return false;
		}

		if (!livePusherContext) {
			initLivePusherContext();
		}

		livePusherContext.start({
			success: () => {
				state.isLiving = true;
				state.liveStatus = '直播中';
				sheep.$helper.toast('直播已开始');
			},
			fail: (error) => {
				console.error('开始推流失败:', error);
				state.errorMsg = error.errMsg || '开始推流失败';
				sheep.$helper.toast('开始推流失败');
			},
		});
	};

	// 停止推流
	const stopPush = () => {
		if (!livePusherContext) return;

		livePusherContext.stop({
			success: () => {
				state.isLiving = false;
				state.liveStatus = '已结束';
				sheep.$helper.toast('直播已结束');
			},
			fail: (error) => {
				console.error('停止推流失败:', error);
				sheep.$helper.toast('停止推流失败');
			},
		});
	};

	// 切换直播状态
	const toggleLive = () => {
		if (state.isLiving) {
			// 确认是否结束直播
			uni.showModal({
				title: '提示',
				content: '确定要结束直播吗？',
				success: (res) => {
					if (res.confirm) {
						stopPush();
					}
				},
			});
		} else {
			startPush();
		}
	};

	// 切换摄像头
	const switchCamera = () => {
		if (!livePusherContext) return;

		livePusherContext.switchCamera({
			success: () => {
				state.devicePosition = state.devicePosition === 'front' ? 'back' : 'front';
				// 后置摄像头时关闭闪光灯
				if (state.devicePosition === 'front' && state.enableFlash) {
					toggleFlash();
				}
			},
		});
	};

	// 切换闪光灯
	const toggleFlash = () => {
		if (!livePusherContext) return;

		// 前置摄像头不支持闪光灯
		if (state.devicePosition === 'front') {
			sheep.$helper.toast('前置摄像头不支持闪光灯');
			return;
		}

		state.enableFlash = !state.enableFlash;
		livePusherContext.toggleTorch({
			success: () => {
				sheep.$helper.toast(state.enableFlash ? '闪光灯已开启' : '闪光灯已关闭');
			},
		});
	};

	// 切换麦克风
	const toggleMute = () => {
		if (!livePusherContext) return;

		state.enableMic = !state.enableMic;
		if (state.enableMic) {
			livePusherContext.resumeBGM();
		} else {
			livePusherContext.pauseBGM();
		}
	};

	// 美颜级别变化
	const onBeautyChange = (e) => {
		state.beauty = e.detail.value;
	};

	// 美白级别变化
	const onWhitenessChange = (e) => {
		state.whiteness = e.detail.value;
	};

	// 清晰度模式变化
	const onModeChange = (e) => {
		state.mode = e.detail.value;
		// 根据清晰度设置码率
		switch (state.mode) {
			case 'SD':
				state.minBitrate = 200;
				state.maxBitrate = 1000;
				break;
			case 'HD':
				state.minBitrate = 600;
				state.maxBitrate = 1500;
				break;
			case 'FHD':
				state.minBitrate = 1000;
				state.maxBitrate = 2500;
				break;
		}
	};

	// 直播状态变化事件
	const onStateChange = (e) => {
		console.log('推流状态变化:', e.detail);
		const { code } = e.detail;
		switch (code) {
			case 1001:
				console.log('已经连接推流服务器');
				break;
			case 1002:
				console.log('已经与服务器握手完毕,开始推流');
				break;
			case 1003:
				console.log('打开摄像头成功');
				break;
			case 1004:
				console.log('录屏启动成功');
				break;
			case 1005:
				console.log('推流动态调整分辨率');
				break;
			case 1006:
				console.log('推流动态调整码率');
				break;
			case 1007:
				console.log('首帧画面采集完成');
				break;
			case 1008:
				console.log('编码器启动');
				break;
			case -1301:
				console.error('打开摄像头失败');
				sheep.$helper.toast('打开摄像头失败');
				break;
			case -1302:
				console.error('打开麦克风失败');
				sheep.$helper.toast('打开麦克风失败');
				break;
			case -1303:
				console.error('视频编码失败');
				sheep.$helper.toast('视频编码失败');
				break;
			case -1304:
				console.error('音频编码失败');
				sheep.$helper.toast('音频编码失败');
				break;
			case -1305:
				console.error('不支持的视频分辨率');
				sheep.$helper.toast('不支持的视频分辨率');
				break;
			case -1306:
				console.error('不支持的音频采样率');
				sheep.$helper.toast('不支持的音频采样率');
				break;
			case -1307:
				console.error('网络断连，且经多次重连抢救无效，更多重试请自行重启推流');
				sheep.$helper.toast('网络断连，请检查网络后重试');
				break;
			case -1308:
				console.error('开始录屏失败，可能是被用户拒绝');
				sheep.$helper.toast('开始录屏失败');
				break;
			case -1309:
				console.error('录屏失败，不支持的Android系统版本，需要5.0以上的系统');
				sheep.$helper.toast('录屏失败，系统版本过低');
				break;
			case -1310:
				console.error('录屏被其他应用打断了');
				sheep.$helper.toast('录屏被其他应用打断');
				break;
			case -1311:
				console.error('Android Mic打开成功，但是录不到音频数据');
				sheep.$helper.toast('麦克风无法录制音频');
				break;
			case -1312:
				console.error('录屏动态切横竖屏失败');
				sheep.$helper.toast('录屏动态切横竖屏失败');
				break;
			case 1101:
				console.log('网络状况不佳：上行带宽太小，上传数据受阻');
				sheep.$helper.toast('网络状况不佳，请检查网络');
				break;
			case 1102:
				console.log('网络断连, 已启动自动重连');
				state.liveStatus = '重连中...';
				break;
			case 1103:
				console.log('硬编码启动失败,采用软编码');
				break;
			case 1104:
				console.log('视频编码失败');
				sheep.$helper.toast('视频编码失败');
				break;
			case 1105:
				console.log('新美颜软编码启动失败，采用老的软编码');
				break;
			case 1106:
				console.log('新美颜软编码启动失败，采用老的软编码');
				break;
			case 3001:
				console.log('RTMP -DNS解析失败');
				sheep.$helper.toast('DNS解析失败');
				break;
			case 3002:
				console.log('RTMP服务器连接失败');
				sheep.$helper.toast('服务器连接失败');
				break;
			case 3003:
				console.log('RTMP服务器握手失败');
				sheep.$helper.toast('服务器握手失败');
				break;
			case 3004:
				console.log('RTMP服务器主动断开，请检查推流地址的合法性或防盗链有效期');
				sheep.$helper.toast('服务器主动断开，请检查推流地址');
				break;
			case 3005:
				console.log('RTMP 读/写失败');
				break;
		}
	};

	// 网络状态监控
	const onNetStatus = (e) => {
		state.netStatus = e.detail;
	};

	// 错误处理
	const onError = (e) => {
		console.error('推流错误:', e.detail);
		state.errorMsg = e.detail.errMsg || '推流发生错误';
		sheep.$helper.toast(`推流错误: ${state.errorMsg}`);
	};

	// 背景音乐开始事件
	const onBgmStart = (e) => {
		console.log('背景音乐开始播放', e);
	};

	// 背景音乐进度事件
	const onBgmProgress = (e) => {
		console.log('背景音乐播放进度', e.detail.progress);
	};

	// 背景音乐完成事件
	const onBgmComplete = (e) => {
		console.log('背景音乐播放完成', e);
	};
</script>

<style lang="scss" scoped>
	.live-streaming-wrap {
		background-color: #000;
		height: 100vh;
		width: 100%;
		position: relative;
		overflow: hidden;
	}

	.live-pusher-container {
		position: relative;
		width: 100%;
		height: 100vh;
	}

	.live-pusher {
		width: 100%;
		height: 100%;
	}

	/* 直播状态栏 */
	.live-status-bar {
		position: absolute;
		top: 100rpx;
		left: 0;
		right: 0;
		display: flex;
		padding: 20rpx 30rpx;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 10;

		.status-item {
			display: flex;
			align-items: center;
			margin-right: 30rpx;

			.status-label {
				font-size: 24rpx;
				color: #ffffff;
				margin-right: 10rpx;
			}

			.status-value {
				font-size: 24rpx;
				color: #ffffff;
			}

			.status-live {
				color: #ff4d4f;
			}
		}
	}

	/* 控制面板 */
	.control-panel {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.7);
		padding: 30rpx;
		z-index: 10;
	}

	/* 美颜控制 */
	.control-group {
		margin-bottom: 30rpx;

		.control-item {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;

			.control-label {
				width: 80rpx;
				font-size: 28rpx;
				color: #ffffff;
			}

			.control-slider {
				flex: 1;
			}
		}
	}

	/* 功能按钮组 */
	.button-group {
		display: flex;
		justify-content: space-around;
		margin-bottom: 30rpx;

		.control-btn {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20rpx;

			.iconfont {
				font-size: 48rpx;
				color: #ffffff;
				margin-bottom: 10rpx;
			}

			.btn-text {
				font-size: 24rpx;
				color: #ffffff;
			}
		}
	}

	/* 清晰度选择器 */
	.quality-selector {
		margin-bottom: 30rpx;

		.selector-label {
			font-size: 28rpx;
			color: #ffffff;
			margin-bottom: 20rpx;
			display: block;
		}

		.radio-group {
			display: flex;
			flex-wrap: wrap;

			.radio-item {
				margin-right: 30rpx;
				display: flex;
				align-items: center;

				.radio-text {
					font-size: 28rpx;
					color: #ffffff;
					margin-left: 10rpx;
				}
			}
		}
	}

	/* 开始/停止直播按钮 */
	.start-btn {
		width: 80%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background: linear-gradient(135deg, #36d1dc 0%, #5b86e5 100%);
		color: #ffffff;
		font-size: 32rpx;
		border-radius: 40rpx;
		margin: 0 auto;
		box-shadow: 0 10rpx 20rpx rgba(54, 209, 220, 0.3);
	}

	.stop-btn {
		background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
		box-shadow: 0 10rpx 20rpx rgba(255, 65, 108, 0.3);
	}

	/* 图标字体 */
	@font-face {
		font-family: 'iconfont';
		src: url('data:font/woff2;charset=utf-8;base64,d09GMgABAAAAAAXMAAsAAAAACwQAAAV+AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHFQGYACDMgqJCIdiATYCJAMUCwwABCAFhGcHSRvSCREVpFGR/UiwbSGPxFBMJJFEYmxMUYiF6IfH035f7s4+wRPUWr/d3fcHsQCJRLMkmkcqiURIJNIkQoVE6IQO9f9f0/4PcDEuYFUhK6yqKmRFVEQVhYzKKnJWVaXOqtxVuauQVbinz7b+bHcC2iwi63H0I7eR3ESuEbkJceN5E2iaNBRrb1/YBHYKNAvEXcFMYJcipYQe6oXKwdKCeAZVPT1KzwN4Gn1//EcujCRVZl70/sOzBRT+An/5RRYt/r+4sTsA6/FMsJXImAMoxHVh6DWcAM0xTJpKvnAJaOpJ/AJ/efzl1y+y/v9PdoxHWk/SP54lUYgGUW8ztjhZfAFRJfkFJlXyCwKqJL8QoYryCxGqJL+IQBXzCwHVVLtRDWWdxDaQJ4D4DkBuQa/qJZJUVVTlRJQkUbTb7ZIrXsLBcFyRqEZHOxyxkRGHI+5wREdGRjnDDvfQUKzDER0eHuWIRjXGRJgYG+/+cjDcj5hxo8aNjY2ZMGHMuLFjxo8ZM378mAkTxo4fP2ZiZMy4caPHjxs9IcKMGzNq/NjRE8eOmjB+9KQJoydOGDVpwqhJk0ZNnjxqypRRU6eOmjZt1PTpMbNmxc6eHTtnTuzcuXHz5sXNnx+3YEH8woXxixbFL14cv2RJ/NKl8cuWxS9fHr9iRfzKlfGrVsWvXh2/Zk382rXx69bFr18fv2FD/MaNiZs2JW7enLhlS+LWrYnbtiVu3564Y0fijh1JO3cm7dqVtHt30p49SXv3Ju3bl7R/f9KBA0kHDyYdOpR0+HDSkSNJR48mHTuWdPx40okTSSdPJp06lXT6dNKZM0lnzyade5R07nHSuSdJ554mnX+WdOF50sUXSZdeJl1+lXTlddLVN0nX3iZdf5d0433SzQ9Jtz4m3f6UdOdz0t0vSfe+Jt3/lvTge9LD4VuPRmw9Hrn1ZNTW01Fbz0ZvPR+z9WLs1stxW6/Gb72esPVm4tbbyVvvpmwdnrp1eNrW4elb7+m0e/fS7t9Pe/Ag7eHDtEeP0h4/Tnv6NO3Zs7Tnz9NevEh7+TLt1au0N2/S3r5Ne/cu7f37tA8f0j5+TPv0Ke3z57QvX9K+fk379i3t+/e0Hz/Sfv5M+/Ur7ffvtD9/0v7+Tfv3L10AyNixI3PXrszdu7P27MnatStr+/asrVuzNm/O2rgxa/36rLVrs1avzlq5MmvFiqxly7KWLMlauDBr/vysuXOzZs/OmjEja9q0rClTsiZPzpo0KWv8+KyxY7NGj84aMSJr2LCs3r2zevbM6t49q0uXrE6dstq3z2rTJqtVq6zmzbOaNMlq2DCrXr2sOnWyatXKqlEjq1q1rMqVsypUyCpXLqtMmaxSpbKKF88qUiSrcOGsggWz8ufPypMnK3furJw5s7Jnz8qaNStLlqzMmTMzZcrMkCEzffr/APWFJPWYemCBAAAAAElFTkSuQmCC')
			format('woff2');
	}

	.iconfont {
		font-family: 'iconfont' !important;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
	}

	.icon-camera-switch:before {
		content: '\e8d0';
	}

	.icon-flash-on:before {
		content: '\e8d9';
	}

	.icon-flash-off:before {
		content: '\e8da';
	}

	.icon-mic:before {
		content: '\e8e0';
	}

	.icon-mic-off:before {
		content: '\e8e1';
	}
</style>
